package com.example.demo.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 10:51 2021/2/2
 * @Modified By:
 */
public class CglibTransactionProxy implements MethodInterceptor {
    private Object target;

    public CglibTransactionProxy(Object object) {
        this.target = object;
    }

    public Object genProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println(method.getName() + "调用前。");
        Object result = methodProxy.invoke(target, args);
        System.out.println(method.getName() + "调用后。");
        return result;
    }
}
